# -*- coding;utf-8 -*-
"""
File name : ReadDoc2List.PY
Program IDE : PyCharm
Create file time: 2022/5/18 19:39
File Create By Author : 朱清闯
已弃用
"""
import docx
from docx.document import Document
from docx.text.paragraph import Paragraph
from docx.image.image import Image
from docx.parts.image import ImagePart
from docx.oxml.shape import CT_Picture
from PIL import Image
import os
import re
from django.conf import settings
from utils.uploadfile import get_new_name


question_number_list = [str(i) + "." for i in range(1, 31)]
# 建立题型选择器
text_head_filling = "、填空题"
text_head_choice = "、选择题"
text_head_SQAS = "、简答题"
type_dict = {text_head_filling: text_head_filling[1::], text_head_choice: text_head_choice[1::],
             text_head_SQAS: text_head_SQAS[1::]}


def get_picture(document: Document, paragraph: Paragraph):
    """
    document 为文档对象
    paragraph 为内嵌图片的某一个段落对象，比如第1段内
    """
    result_list = []
    img_list = paragraph._element.xpath('.//pic:pic')
    if len(img_list) == 0 or not img_list:
        return
    for i in range(len(img_list)):
        img: CT_Picture = img_list[i]
        embed = img.xpath('.//a:blip/@r:embed')[0]
        related_part: ImagePart = document.part.related_parts[embed]
        image: Image = related_part.image
        result_list.append(image)
    return result_list


def read_docx_2_question_list(d: Document):
    start_row = 0
    questions_list = []  # 存放所有题目
    question_dict = {"content": "", "answer": "", "explain": "", "type": "", "pictures": "", "pictures_explain": "",
                     "reference": "", "add_time": "", "difficulty_level": 3, "knowledgepoint": -1,
                     "knowledgepoint_value": '待选'}
    explain_image_url_list = ""
    result_path = settings.IMAGE_URL
    first = True
    current_type = "选择题"
    # 第一行试卷的标题填入“reference”字段
    paragraph = d.paragraphs[0]
    reference = ""
    if paragraph.text.strip():
        reference = paragraph.text.strip()
    question_dict["reference"] = reference
    # 第二行为试卷的标题，字典中填入“reference”字段
    paragraph = d.paragraphs[1]
    add_time = ""
    if paragraph.text.strip():
        add_time = paragraph.text.strip()
    question_dict["add_time"] = add_time
    # 从第一题开始收集题目
    for start_row in range(len(d.paragraphs)):
        paragraph = d.paragraphs[start_row]
        if paragraph.text.strip()[1:5:] in type_dict.keys():
            break

    question_type_rule = r"^[一二三四]、(.+)\（"  # 匹配题型，如一、选择题
    question_number_rule = r"^\d+.(.+)"  # 匹配小题号，如段首以1.开头
    answer_rule = r"^【答案】(.+)"  # 匹配答案，如【答案】xxx
    explain_rule = r'^【解析】(.+)'  # 匹配解析，如【解析】xxx
    difficulty_rule = r'^【难度】(\d)'
    # 遍历每个段落
    for i in range(start_row, len(d.paragraphs)):
        # 读取每个段落的图片
        paragraph = d.paragraphs[i]
        # 获取所有的文本内容
        if get_picture(d, paragraph):                                 #匹配到插图
            content_image_url_list = ""
            image_list = get_picture(d, paragraph)
            if image_list:
                for j in range(len(image_list)):                        #遍历每一张图片
                    if not os.path.exists(result_path):
                        os.makedirs(result_path)
                    img_name = get_new_name() + ".jpg"
                    img_server_url = settings.SERVER_DEV_URL + settings.IMAGE_URL + img_name
                    with open(f'{result_path}/{img_name}', 'wb') as f:      #保存到本地
                        f.write(image_list[j].blob)
                    if question_dict['explain']:                        #题目内容的插图
                        question_dict['pictures_explain'] += img_server_url + "-"
                    elif question_dict['content']:                        #解析的插图
                        question_dict["pictures"] += img_server_url + "-"
                if content_image_url_list:                              #图片的个数
                    content_image_url_list += str(len(image_list))
                else:
                    explain_image_url_list += str(len(image_list))
        elif not paragraph.text.strip():          #跳过空白段落
            continue
        elif re.match(question_type_rule, paragraph.text.strip()):                  #匹配题型，如二、填空题
            current_type_new = re.match(question_type_rule, paragraph.text.strip()).group(1)
            current_type = current_type_new
            continue
        else:
            if re.match(question_number_rule, paragraph.text.strip()):          #匹配到题号，比如1.以下xxx
                if not first:                                           #不是第一题
                    questions_list.append(question_dict)                    #先将上一题添加到列表，再设置新题各属性
                    question_dict = {"content": "", "answer": "", "explain": "", "type": current_type, "pictures": "",
                                     "pictures_explain": "", "reference": reference, "add_time": add_time,
                                     "difficulty_level": 3, "knowledgepoint": -1, "knowledgepoint_value": '待选'}
                else:
                    first = False
                content = re.match(question_number_rule, paragraph.text, flags=re.S).group(1)
                question_dict['type'] = current_type
                question_dict['content'] = content + "<br>"
            elif re.match(answer_rule, paragraph.text.strip()):                 #匹配到答案
                answer = re.match(answer_rule, paragraph.text.strip(), flags=re.S).group(1)
                question_dict['answer'] = answer + "<br>"
            elif re.match(explain_rule, paragraph.text.strip()):                #匹配到解析
                explain = re.match(explain_rule, paragraph.text.strip(), flags=re.S).group(1)
                question_dict['explain'] = explain + "<br>"
            elif re.match(difficulty_rule, paragraph.text.strip()):             #匹配到难度
                difficulty_level = re.match(difficulty_rule, paragraph.text.strip(), flags=re.S).group(1)
                question_dict['difficulty_level'] = int(difficulty_level)
            else:                                                           #非空行的有文字内容，则拼接到各属性中
                if question_dict['explain']:
                    question_dict['explain'] += paragraph.text + "<br>"
                elif question_dict['answer']:
                    question_dict['answer'] += paragraph.text + "<br>"
                elif question_dict['content']:
                    question_dict['content'] += paragraph.text + "<br>"
        if question_dict['pictures'] and question_dict['pictures'][-1] == "-":
            question_dict['pictures'] = question_dict['pictures'][:-1:]
        if question_dict['pictures_explain'] and question_dict['pictures_explain'][-1] == "-":
            question_dict['pictures_explain'] = question_dict['pictures_explain'][:-1]
    questions_list.append(question_dict)
    print(questions_list)
    return questions_list


if __name__ == "__main__":
    document = docx.Document('test.docx')
    data_list = read_docx_2_question_list(document)
    print(data_list)
